#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Zhangcl
from crm.permissions import permission_list
from django.shortcuts import HttpResponse, redirect, render
from django.core.urlresolvers import resolve


def perm_check(*args, **kwargs):
    request = args[0]
    if request.user.is_authenticated():
        for permission_name, v in permission_list.perm_dic.items():
            print(permission_name, v)
            url_matched = False
            if v['url_type'] == 1:
                if v['url'] == request.path:  # 绝对url匹配上了
                    url_matched = True
            else:
                # 把绝对的url请求转成相对的url_name
                resolve_url_obj = resolve(request.path)
                current_url_name = resolve_url_obj.url_name
                print('请求的相对路径',current_url_name)
                if current_url_name == v['url']:
                    url_matched = True

            if url_matched:
                if v['method'] == request.method:
                    arg_metched = True
                    for request_arg in v['args']:
                        request_method_func = getattr(request,v['method'])
                        if not request_method_func.get(request_arg):
                            arg_metched = False
                    if arg_metched:  # 走到这里，仅代码这个请求和这条权限的定义规则 匹配上了
                        if request.user.has_perm(permission_name):
                            print("有权限", permission_name)
                            return True

    else:
        return redirect("/account/login/")


def check_permission(func):
    def inner(*args, **kwargs):
        print("--permission:", *args, **kwargs)
        print("--func:", func)
        if perm_check(*args, **kwargs) is True:
            return func(*args, **kwargs)
        else:
            return HttpResponse("没权限")

    return inner
